!(function () {
    const DEG = Math.PI / 180;
    var Gouzi = window.Gouzi = function () {
        if (game.gouzi) {
            return game.gouzi
        }
        // 钩子状态: pending：等待； down: 出钩 up: 收钩
        this.status = 'pending';

        // 钩子初始长度
        this.rotateDegMax = 80;
        this.gouziLong = 60;

        // 钩子起始点，相当于圆心
        this.startX = game.canvasWidth / 2;
        this.startY = 30;

        // 钩子初始旋转角度值，即默认左边开始荡
        this.rotateDeg = -this.rotateDegMax;

        // 钩子方向值的控制 +1 -1代表不同的方向，每达到80或-80的时候转变方向
        this.rotateZhengfu = -1;

        // 钩子终点位置
        this.endX = 0; // endX一直都是不变的，因为钩子的荡漾动作是旋转得到的 
        this.endY = this.gouziLong;

        // 钩子图片参数
        this.gouziW = 36;
        this.gouziH = 28;

        // 托管到game上
        game.gouzi = this;
    }

    Gouzi.prototype.render = function () {
        game.ctx.save();
        game.ctx.beginPath();
        game.ctx.lineWidth = 4;
        game.ctx.lineCap = 'round';
        game.ctx.translate(this.startX, this.startY);
        game.ctx.rotate(this.rotateDeg * -DEG); // -DEG表示逆时针旋转
        game.ctx.moveTo(0, 0);
        game.ctx.lineTo(this.endX, this.endY);
        game.ctx.stroke();
        game.ctx.drawImage(game.R.zhuazi, 0, 0, 45, 35, this.endX - this.gouziW / 2, this.endY, this.gouziW, this.gouziH);
        game.ctx.restore();
    }

    Gouzi.prototype.update = function () {
        let endX;
        switch (this.status) {
            case 'pending':
                if (Math.abs(this.rotateDeg) == this.rotateDegMax) {
                    this.rotateZhengfu = -this.rotateZhengfu;
                }
                this.rotateDeg += 1 * this.rotateZhengfu;
                break;
            case 'down':
                // 如何判断该不该收钩子呢？
                // 第1种是钩子抓到了就收钩子（通过endY + rotateDeg + sin公式计算出endX）
                this.endY += 3;
                endX = this.startX + (this.endY * Math.sin(this.rotateDeg * DEG));
                let wawaIndex = game.wawaArr.findIndex(d => (d.y - d.h) < this.endY && this.endY < d.y && d.x < endX && endX < (d.x + d.w));
                if (wawaIndex != -1) {
                    // 移除娃娃
                    game.wawaArr.splice(wawaIndex, 1);
                    // 如果全被抓光了就end游戏
                    if (game.wawaArr.length == 0) {
                        game.end();
                    }
                    this.status = 'up';
                }
                // 第2种是钩子长到最长距离然后开始收钩子
                else if (this.endY >= game.canvasHeight - this.startY - this.gouziH) {
                    this.status = 'up';
                }

                break;
            case 'up':
                this.endY -= 3;
                if (this.endY <= this.gouziLong) {
                    this.endY = this.gouziLong;
                    this.status = 'pending';
                }
                break;
            default:
                return;
        }
    }

})()